//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.IO;
using OpenLS.Spreadsheet.Expressions;
using OpenLS.Spreadsheet.Formats.Biff.Tokens;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class SharedFormulaRecord : WorksheetLevelRecord, IFormulaRecord
    {
        private RangeAddress8 _address;
        private SharedParsedFormula _formula;

        public SharedFormulaRecord(SharedExpression sharedExpression, BiffWriterWorkbookContext context, Cell cell)
        {
            this._address = (RangeAddress8) sharedExpression.Address;
            _formula = SharedParsedFormula.GetFormulaValue<SharedParsedFormula>(context, sharedExpression.TopLeftExpression, cell);

        }

        public SharedFormulaRecord()
        {
        }

        #region IFormulaRecord Members

        public object FormulaResult { get; set; }

        #endregion

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.ShrFmla; }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            _address.Write(context.Writer);
            context.Write((byte)0);
            context.Write((byte)0); //\\ sure?
            _formula.Write(context.Writer);
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            _address.Read( (context.Reader));// =  AddressHelper.ReadAddress8(context.Reader);
            context.ReadUInt16();
           // int formulaLength = reader.ReadUInt16();
            _formula = new SharedParsedFormula();
            _formula.Read(new FormulaReadContext(context.Reader, FormulaReadContextType.Default));
        }

        internal override void Apply(BiffReaderWorksheetContext context)
        {
            RangeAddress rangeAddress = (RangeAddress) _address;
            Cell cell = (context.Worksheet[rangeAddress.TopLeft]);
            context.WorkbookContext.GetActions(ActionType.SharedFormula).Add(delegate
                                                    {
                                                        context.SharedFormulas.Add(
                                                            new SharedExpression(rangeAddress,
                                                                                 _formula.GetExpression(context, cell)));
                                                    });
        }
    }
}